<?php
/**
 * WeUser.php
 */
class Domain_WeUser
{
    /**
     * 用户注册
     * @param $data
     * @return array res
     * @desc wjp 2017-12-26
     * @throws PhalApi_Exception_InternalServerError
     */
    public function Register($data){
        $model = new Model_WeUser();
        $tokenModel = new Model_UserToken();
        $hasUser = $model -> get_logUserinfo($data['phone']);
        if($hasUser != -1) {
            $res = DI()->ResCode->get("WE.hasUser");
            return $res;
        }
        if($data['code'] != 1234){
            $res = DI()->ResCode->get("WE.codeError");
            return $res;
        }
        unset($data['code']);
        $userInfo = $model -> insertUser($data);
        $token = md5($data['phone'].time().$data['id']);
        $tokenModel->deleteToken($userInfo['id'],1);
        $tokenModel->insertToken($userInfo['id'],1,$token);
        DI() -> redis -> set_time($token,$userInfo['id'],3600);
        $userInfo['accessToken'] = $token;
        $res = DI()->ResCode->get("WE.Success");
        $res["data"] = $userInfo;
        return $res;
    }

    /**
     * 用户登录
     * @param $phone
     * @param $pwd
     * @return array res
     * @desc wjp 2018-1-2
     * @throws PhalApi_Exception_InternalServerError
     */
    public function Login($phone,$pwd){
        $model = new Model_WeUser();
        $tokenModel = new Model_UserToken();
        $hasUser = $userInfo = $model -> getPhonePwd($phone,$pwd);

        if($hasUser == null || $hasUser == -1) {
            $res = DI()->ResCode->get("WE.hasUser");
            return $res;
        }
        $token = md5($hasUser['phone'].time().$hasUser['id']);
        $tokenModel->deleteToken($userInfo['id'],1);
        DI() -> redis -> set_time($token,$userInfo['id'],3600);
        $tokenModel->insertToken($userInfo['id'],1,$token);
        $userInfo['accessToken'] = $token;
        return $userInfo;
    }

    /**
     * 退出登录
     * @throws PhalApi_Exception_InternalServerError
     */
    public function LoginOut(){
        $session = new Model_Session();
        if(isset($_SESSION['user_info']))
            $session -> Update(['game_id' => $_SESSION['user_info']['game_id']],['session_id'=>0,'out_time'=>0]);
        $_SESSION=[];
    }

    /**
     * 修改密码
     * @param $data
     * @return mixed
     */
    public function ChangePWD($data){
        $model = New Model_User();
        if(!isset($_SESSION['user_info']))
            return DI()->ResCode->get("GZH.LoginError5");
        $user_info = $model -> selectOne(['game_id'=>$_SESSION['user_info']['game_id']]);
        if($user_info['pwd'] != md5($data['pwd']))
            return DI()->ResCode->get("GZH.LoginError3");
        $model -> Update(['game_id'=>$_SESSION['user_info']['game_id']],['pwd'=>md5($data['new_pwd'])]);
        return DI()->ResCode->get("GZH.Success");
    }


}